package com.anjho.bean;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.anjho.dao.DAOUser;
import com.anjho.exceptions.InvalidLoginException;
import com.anjho.pojo.Page;
import com.anjho.pojo.User;
import com.anjho.utils.Constants;

/**
 * @author Jhonathan Corrêa
 * @version 0.9
 * @since 2012/02/23
 * @category ManagedBean
 * 
 *           ManagedBean Responsável pelo processo de autenticação
 * 
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean extends GenericBean implements Serializable {

	private static final long serialVersionUID = -1982748532975289462L;
	private boolean logged = false;
	private User user;

	public LoginBean() {
		super();
		init();
	}

	private void init() {
		this.user = new User();
	}

	private String redirect() {
		return "/pages/index.jsf?faces-redirect=true";
	}

	public String onLoginClick() {
		String url = null;
		try {
			DAOUser daoUser = new DAOUser();
			this.user = daoUser.getUser(this.user);
			daoUser = null;
			if (this.user == null){
				throw new InvalidLoginException("Login e senha inválidos!");
			}
			
			this.setLogged(true);
			this.putInSession(Constants.LOGGED_USER, this.user);
			url = redirect();
		} catch (InvalidLoginException e) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Informações inválidas", e.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		} catch (Exception e) {
			FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", e.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, facesMsg);
		}
		return url;
	}
	
	public String logout() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(false);
		session.invalidate();
		return Constants.LOGIN_PAGE;
	}
	
	public User getUser(){
		return this.user;
	}
	
	public void setUser(User user){
		this.user = user;
	}
	
	public boolean hasPermission(String page){
		Page pemitedPage = new Page(page);
		if (this.user.getProfile().getPages().contains(pemitedPage)){
			return true;
		}
		return false;
	}
	
	public boolean isLogged(){
		return this.logged;
	}
	
	private void setLogged(boolean logged){
		this.logged = logged;
	}
	
}
